package com.atguigu.spring.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class MyInterceptor01 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor01 preHandle 执行了~~~");

        // 假设：是否放行的过滤条件是，请求参数中是否携带了 monster，而且 monster 的值是 peter
        // 1、获取请求参数
        String monster = request.getParameter("monster");

        // 2、检查请求参数的值，根据判断结果决定是否放行
        if ("peter".equals(monster)) {
            // 3、满足过滤条件，则放行
            return true;
        } else {

            // 4、不满足过滤条件，返回响应
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("不满足条件，不能查看私密资源~~~");

            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor01 postHandle 执行了~~~");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor01 afterCompletion 执行了~~~");
    }
}
